package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PageHelp;
import com.fz.us.admin.base.bean.search.page.PagePaging;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.Remind;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.RemindService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.oa.core.entity.com.Task;
import com.fz.us.oa.core.entity.com.TaskFeedback;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.TaskFeedbackService;
import com.fz.us.oa.core.service.com.TaskService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/24.
 */
@Controller
@RequestMapping(value = "/com/task")
public class TaskController extends BaseController {
    private static final long serialVersionUID = 4407285971535461427L;

    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskFeedbackService taskFeedbackService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private UserService userService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private FileManagerService fileManagerService;
    @Autowired
    private RemindService remindService;

    private Calendar calendar = new GregorianCalendar();

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> dictItems = getDictItems(user,"taskPrj");
        if (StringUtils.isNotEmpty(keyId)){
            Task task=taskService.get(keyId);
            String fileId ="";
            if(task.getFile() != null && task.getFile().size()>0){
                for(FileManage f:task.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("fileId", fileId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("task", task);

            String priority = "一般";
            if(task.getPriority()==1){
                priority = "重要";
            } else if (task.getPriority()==2) {
                priority = "紧急";
            }

            model.addAttribute("priority",priority);

        }
        model.addAttribute("dictItems", dictItems);
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/task_input";
    }

    /**
     * 修改页面
     */
    @RequestMapping(value = "revise/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String revise(@CurrentUser User user, Model model,
                         @PathVariable String keyId) {
        model.addAttribute("user",user);

        ArrayList<DictItem> dictItems = getDictItems(user,"taskPrj");
        if(dictItems.size()>0){
            model.addAttribute("dictItems",dictItems);
        }

        Task task = taskService.get(keyId);
        String fileId ="";
        if(task.getFile() != null && task.getFile().size()>0){
            for(FileManage f:task.getFile()){
                fileId+=f.getId()+",";
            }
        }
        model.addAttribute("fileId", fileId);
        model.addAttribute("keyId", keyId);
        model.addAttribute("task",task);
        model.addAttribute("handle","revise");

        String priority = "一般";
        if(task.getPriority()==1){
            priority = "重要";
        } else if (task.getPriority()==2) {
            priority = "紧急";
        }

        model.addAttribute("priority",priority);
        return "/com/task_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            Task task = taskService.get(keyId);
            if(task.getFile() != null && task.getFile().size()>0){
                for(FileManage f:task.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            if(!task.getProcessState().name().equals("Finished")&&!task.getProcessState().name().equals("Destroy")){
                TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
                int stepNo = taskEntity.getStepNo();
                String isEdit =  isEdit(keyId);
                model.addAttribute("stepNo", stepNo);
                model.addAttribute("isEdit", isEdit);
            }
            model.addAttribute("task", task);
            model.addAttribute("fileId", fileId);

            String priority = "一般";
            if(task.getPriority()==1){
                priority = "重要";
            } else if (task.getPriority()==2) {
                priority = "紧急";
            }
            model.addAttribute("priority",priority);

        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/task_read";
    }

    /**
     * 历史文档的只读页面
     */
    @RequestMapping(value = "readhistory/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String readhistory(@CurrentUser User user, Model model,
                              @PathVariable String keyId) {

        Task task = taskService.get(keyId);
        model.addAttribute("keyId", keyId);
        model.addAttribute("task",task);
        model.addAttribute("user",user);
        String fileId ="";
        if(task.getFile() != null && task.getFile().size()>0){
            for(FileManage f:task.getFile()){
                fileId+=f.getId()+",";
            }
        }
        model.addAttribute("fileId", fileId);

        String priority = "一般";
        if(task.getPriority()==1){
            priority = "重要";
        } else if (task.getPriority()==2) {
            priority = "紧急";
        }

        model.addAttribute("priority",priority);
        return "/com/task_readhistory";
    }

    /**
     * 保存Model数据
     */
    private Task saveModel(User user, String keyId, String dictItemId, String relateTaskIds, String name,String detail,
                           String leaderIds,String memberIds,String datPlanStart, String datPlanEnd,
                           String datWarning, String priority, String fileIds) {

        Task task = null;
        if (StringUtils.isBlank(keyId)) {
            task = new Task();
            task.setCreater(user);
            task.setCompany(user.getCompany());
        } else {
            task = taskService.get(keyId);
        }

        if (StringUtils.isNotBlank(dictItemId)) {
            DictItem dictItem = dictItemService.get(dictItemId);
            task.setDictItem(dictItem);
        }

        if(StringUtils.isNotBlank(relateTaskIds)){
            String[] tasks = StringUtils.split(relateTaskIds,",");
            HashSet<Task> objs = new HashSet<Task>();
            for (String id : tasks) {
                Task relateTask = taskService.get(id);
                objs.add(relateTask);
            }
            task.setRelateTasks(objs);
        }

        if (StringUtils.isNotBlank(name)) {
            task.setName(name);
        }

        if (StringUtils.isNotBlank(detail)) {
            task.setDetail(detail);
        }

        if (StringUtils.isNotBlank(leaderIds)) {
            task.setLeadersIds(leaderIds);
            String[] uids = StringUtils.split(leaderIds,",");
            HashSet<User> users = new HashSet<User>();
            for (String uid : uids) {
                User u = userService.get(uid);
                users.add(u);
            }
            task.setLeaders(users);
        }

        if (StringUtils.isNotBlank(memberIds)) {
            String[] uids = StringUtils.split(memberIds,",");
            HashSet<User> users = new HashSet<User>();
            for (String uid : uids) {
                User u = userService.get(uid);
                users.add(u);
            }
            task.setMembers(users);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(datPlanStart)) {
            try {
                task.setDatPlanStart(sdf.parse(datPlanStart));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(datPlanEnd)) {
            try {
                task.setDatPlanEnd(sdf.parse(datPlanEnd));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(datWarning)) {
            try {
                task.setDatWarning(sdf.parse(datWarning));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (StringUtils.isNotBlank(priority)) {
            task.setPriority(Integer.valueOf(priority));
        }

        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        task.setFile(fileManageList);

        if (task.getForm() == null) {
            task.setForm("任务发起登记表");
        }

        return task;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId, String dictItemId, String relateTaskIds, String name,String detail,
                       String leaderIds,String memberIds,String datPlanStart, String datPlanEnd,
                       String datWarning, String priority,String fileIds){

        Map<String,Object> rMap=new HashMap<String,Object>();
        Task task = saveModel(user,keyId,dictItemId,relateTaskIds,name,detail,leaderIds,memberIds,datPlanStart,datPlanEnd,datWarning,priority,fileIds);
        task.setNumStatus(0);
        if(StringUtils.isNotEmpty(keyId)){
            taskService.update(task);
            rMap.put("message", "更新成功");
        } else {
            taskService.save(task, "com.fz.us.oa.core.entity.com.Task");
            rMap.put("message","保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,String dictItemId, String relateTaskIds, String name,String detail,
                         String leaderIds,String memberIds,String datPlanStart, String datPlanEnd,
                         String datWarning, String priority, String fileIds, String curDutyId, String comment){

        Map<String,Object> rMap=new HashMap<String,Object>();
        Task task = saveModel(user,keyId,dictItemId,relateTaskIds,name,detail,leaderIds,memberIds,datPlanStart,datPlanEnd,datWarning,priority,fileIds);
        task.setTxtStatus("流转中");

        if (StringUtils.isNotEmpty(keyId)) {
            taskService.approve(task, dutyService.get(curDutyId), comment);
        } else {
            taskService.commit(task, "com.fz.us.oa.core.entity.com.Task", dutyService.get(curDutyId));
        }

        if(task.getProcessState().name().equals("Finished")){
            doFinished(task);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Task task = taskService.get(keyId);
        taskService.approve(task, dutyService.get(curDutyId), comment);

        if(task.getProcessState().name().equals("Finished")){
            doFinished(task);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(Task task){
        for(User user1:task.getLeaders()){
            Remind remind = new Remind();
            remind.setUser(user1);
            remind.setBussinessKey("task");
            remind.setKeyId(task.getId());
            remind.setContent("您被分配为"+task.getName()+"任务责任人，请查看");
            remindService.save(remind);
        }
        for(User user2:task.getMembers()){
            Remind remind1 = new Remind();
            remind1.setUser(user2);
            remind1.setBussinessKey("task");
            remind1.setKeyId(task.getId());
            remind1.setContent("您有新的相关任务请查看");
            remindService.save(remind1);
        }

        task.setNumStatus(1);
        task.setTxtStatus("执行中");
        taskService.update(task);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Task task = taskService.get(keyId);
            taskService.back(task, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message", "退回成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Task task = taskService.get(keyId);
            taskService.deny(task, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }


    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    @RequestParam() int catalog,
                                    @RequestParam(required = false) String updateUnid,
                                    @RequestParam(required = false) String prjId,
                                    @RequestParam(required = false) String userId,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order =  Order.order("createTime", SearchEnum.OrderType.desc);
        SearchResultPaging searchResult = null;


        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        rules.add(RuleHelper.eq("company", company));   // 所在的公司
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));    // 文档为有效的
        if (updateUnid!=null && !updateUnid.isEmpty()) {
            rules.add(RuleHelper.eq("updateUnid", updateUnid));
            rules.add(RuleHelper.eq("txtStatus", "历史"));
        } else {
            rules.add(RuleHelper.ne("txtStatus", "历史"));
        }

        if (!StringUtils.isEmpty(prjId)) {
            rules.add(RuleHelper.eq("dictItem.id", prjId));   // 所属项目
        }

        if (!StringUtils.isEmpty(userId)) { // 显示该组员的全部任务或项目内的所有任务
            rules.add(RuleHelper.or(
                    RuleHelper.sql("'" + userId + "' in (select leader_id from task_leader where task_id = this_.id )"),
                    RuleHelper.sql("'" + userId + "' in (select member_id from task_member where task_id = this_.id )")
            ));
        }

        switch (catalog) {
            case 2:
                rules.add(RuleHelper.eq("txtStatus", "执行中"));
                break;
            case 3:
                rules.add(RuleHelper.eq("txtStatus", "完成待验收"));
                break;
            case 4:
                rules.add(RuleHelper.eq("txtStatus", "验收完成"));
                break;
            case 5:
                rules.add(RuleHelper.sql("'" + user.getId() + "' in (select leader_id from task_leader where task_id = this_.id )"));
                break;
            case 6:
                rules.add(RuleHelper.sql("'" + user.getId() + "' in (select member_id from task_member where task_id = this_.id )"));
                break;
            case 7:
                rules.add(RuleHelper.eq("creater.id", user.getId()));
                break;
        }


//        Map<String,Object> params = new HashMap<String,Object>();
//        params.put("company", company);
//        params.put("state", new BaseEnumManager.StateEnum[]{BaseEnumManager.StateEnum.Enable, BaseEnumManager.StateEnum.Delete});
        //所有单子
//        searchResult = taskService.paging(null, rules, order,
//                "com.fz.us.oa.core.entity.com.Infile",
//                new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished}, null);

        searchResult = taskService.findPagingBySearch(null, rules, order);

        List<Task> taskList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Task task: taskList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",task.getId());
            rMap.put("dictItemName",task.getDictItem().getName());
            rMap.put("name",task.getName());
            String leaders="";
            for(User user1:task.getLeaders()){
                leaders+=user1.getName()+",";
            }
            rMap.put("leaders",leaders.substring(0, leaders.length() - 1));
            rMap.put("datPlanStart",DataUtil.DateToString(task.getDatPlanStart()));
            rMap.put("datPlanEnd",DataUtil.DateToString(task.getDatPlanEnd()));
            switch (task.getPriority()){
                case 0:rMap.put("priority","一般");break;
                case 1:rMap.put("priority","重要");break;
                case 2:rMap.put("priority","紧急");break;
            }
            rMap.put("txtStatus",task.getTxtStatus());
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 列表 日历上的
     */
    @RequestMapping(value = "listCalendar", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> listCalendar(@CurrentUser User user, @RequestParam(required = false) String prjId, @RequestParam(required = false) String userId,
                                            @RequestParam() int catalog, @RequestParam() String start, @RequestParam() String end) throws ParseException{
        Company company = user.getCompany();
        // 排序
        Order order =  Order.order("createTime", SearchEnum.OrderType.desc);
        SearchResultPaging searchResult = null;

        List<Rule> rules = new ArrayList<Rule>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        rules.add(RuleHelper.or(
                RuleHelper.and(RuleHelper.ge("datPlanStart", sdf.parse(start)),RuleHelper.le("datPlanStart", sdf.parse(end))),
                RuleHelper.and(RuleHelper.ge("datPlanEnd", sdf.parse(start)),RuleHelper.le("datPlanEnd", sdf.parse(end)))
        ));

        rules.add(RuleHelper.ne("txtStatus", "历史"));
        rules.add(RuleHelper.eq("company", company));   // 所在的公司
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));    // 文档为有效的

        if (!StringUtils.isEmpty(prjId)) {
            rules.add(RuleHelper.eq("dictItem.id", prjId));   // 所属项目
        }

        if (!StringUtils.isEmpty(userId)) { // 显示该组员的全部任务或项目内的所有任务
            rules.add(RuleHelper.or(
                    RuleHelper.sql("'" + userId + "' in (select leader_id from task_leader where task_id = this_.id )"),
                    RuleHelper.sql("'" + userId + "' in (select member_id from task_member where task_id = this_.id )")
            ));
        }

        switch (catalog) {
            case 2:
                rules.add(RuleHelper.eq("txtStatus", "执行中"));
                break;
            case 3:
                rules.add(RuleHelper.eq("txtStatus", "完成待验收"));
                break;
            case 4:
                rules.add(RuleHelper.eq("txtStatus", "验收完成"));
                break;
            case 5:
                rules.add(RuleHelper.sql("'" + user.getId() + "' in (select leader_id from task_leader where task_id = this_.id )"));
                break;
            case 6:
                rules.add(RuleHelper.sql("'" + user.getId() + "' in (select member_id from task_member where task_id = this_.id )"));
                break;
            case 7:
                rules.add(RuleHelper.eq("creater.id", user.getId()));
                break;
        }


//        Map<String,Object> params = new HashMap<String,Object>();
//        params.put("company", company);
//        params.put("state", new BaseEnumManager.StateEnum[]{BaseEnumManager.StateEnum.Enable, BaseEnumManager.StateEnum.Delete});
        //所有单子
//        searchResult = taskService.paging(null, rules, order,
//                "com.fz.us.oa.core.entity.com.Infile",
//                new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished}, null);

        searchResult = taskService.findPagingBySearch(null, rules, order);

        List<Task> taskList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Task task: taskList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(task.getId())?"":task.getId());
            rMap.put("name", StringUtils.isEmpty(task.getName())?"":task.getName());

            String strStart = "";
            String strEnd = "";
            if (task.getDatPlanStart()!=null) {
                strStart = sdf.format(task.getDatPlanStart());
            }

            if (task.getDatPlanEnd()!=null) {
//            strEnd = sdf.format(entity.getDatPlanEnd());
                calendar.setTime(task.getDatPlanEnd());
                calendar.add(calendar.DATE,1);  //把日期往后增加一天.整数往后推,负数往前移动
                strEnd = sdf.format(calendar.getTime());   //这个时间就是日期往后推一天的结果
            }

            Date now = new Date();
            String strNow = sdf.format(now);

            if(strNow.compareTo(strEnd)>0){  // 已超时
                rMap.put("className", "purple");
            } else if (strNow.compareTo(strStart)>0) {   // 进行中
                rMap.put("className", "warning");
            } else {    // 未开始
                rMap.put("className", "mint");
            }

            rMap.put("start", strStart);
            rMap.put("end", strEnd);
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 列表 历史
     */
    @RequestMapping(value = "listHistory", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> listHistory(@CurrentUser User user,
                                    @RequestParam(required = false) String updateUnid,
                                           String keyId,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order =  Order.order("createTime", SearchEnum.OrderType.desc);
        SearchResultPaging searchResult = null;


        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        rules.add(RuleHelper.eq("company", company));   // 所在的公司
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));    // 文档为有效的
        if (updateUnid!=null && !updateUnid.isEmpty()) {
            rules.add(RuleHelper.eq("updateUnid", updateUnid));
            rules.add(RuleHelper.eq("txtStatus", "历史"));
        } else {
            rules.add(RuleHelper.eq("updateUnid", keyId));
            rules.add(RuleHelper.eq("txtStatus", "历史"));
        }


//        Map<String,Object> params = new HashMap<String,Object>();
//        params.put("company", company);
//        params.put("state", new BaseEnumManager.StateEnum[]{BaseEnumManager.StateEnum.Enable, BaseEnumManager.StateEnum.Delete});
        //所有单子
//        searchResult = taskService.paging(null, rules, order,
//                "com.fz.us.oa.core.entity.com.Infile",
//                new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished}, null);

        searchResult = taskService.findPagingBySearch(null, rules, order);

        List<Task> taskList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Task task: taskList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",task.getId());
            rMap.put("dictItemName",task.getDictItem().getName());
            rMap.put("name",task.getName());
            String leaders="";
            for(User user1:task.getLeaders()){
                leaders+=user1.getName()+",";
            }
            rMap.put("leaders",leaders.substring(0, leaders.length() - 1));
            rMap.put("datPlanStart",DataUtil.DateToString(task.getDatPlanStart()));
            rMap.put("datPlanEnd",DataUtil.DateToString(task.getDatPlanEnd()));
            switch (task.getPriority()){
                case 0:rMap.put("priority","一般");break;
                case 1:rMap.put("priority","重要");break;
                case 2:rMap.put("priority","紧急");break;
            }
            rMap.put("txtStatus",task.getTxtStatus());
            rMap.put("dateApply",DataUtil.DateToString(task.getCreateTime()));
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 完成修改操作
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public Object update(@CurrentUser User user,
                         @RequestParam(required = false) String keyId, String dictItemId, String relateTaskIds, String name,String detail,
                         String leaderIds,String memberIds,String datPlanStart, String datPlanEnd,
                         String datWarning, String priority, String fileIds) throws ParseException {

        String unid = "";
        if (StringUtils.isBlank(keyId)) {
            return ajaxJson(resultService.fail("原业务数据已丢失！"));
        }

        Task taskOld = taskService.get(keyId);

        // 如果该任务下已经有了反馈单，则应该不允许修改该任务
        List<Rule> rules = new ArrayList<Rule>();
        rules.add(RuleHelper.eq("company", user.getCompany()));   // 所在的公司
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));    // 文档为有效的
        rules.add(RuleHelper.eq("task.id", taskOld.getId()));

        SearchResultPaging searchResult = taskFeedbackService.findPagingBySearch(null, rules, null);

        List<TaskFeedback> list = new ArrayList<TaskFeedback>();
        if (searchResult != null) {
            list = searchResult.getList();
            if (list.size()>0) {
                return ajaxJson(resultService.fail("该任务下已经有了反馈单，不允许修改该任务！"));
            }
        }

        taskOld.setNumStatus(-1);
        taskOld.setTxtStatus("历史");
        taskOld.setProcessState(FlowEnum.ProcessState.Destroy);
        taskOld.setDateUpdate(new Date());
        if (taskOld.getUpdateUnid() == null) {
            unid = keyId;
            taskOld.setUpdateUnid(keyId);
        } else {
            unid = taskOld.getUpdateUnid();
        }
        taskService.saveEntity(taskOld);

        Task task = saveModel(user,"",dictItemId,relateTaskIds,name,detail,leaderIds,memberIds,datPlanStart,datPlanEnd,datWarning,priority,fileIds);

        if(task == null){
            return ajaxJson(resultService.fail("保存业务数据失败！"));
        }

        task.setDateApply(new Date());
        task.setNumStatus(1);
        task.setProcessState(FlowEnum.ProcessState.Finished);
        task.setTxtStatus("执行中");

        task.setUpdateUnid(unid);
        taskService.saveEntity(task);

        /*  把原来的任务反馈表放到修改后的任务下
        SearchResultPaging searchResult = taskFeedbackService.pagingEntity(PageHelp.page(1, 500), null, null, user.getCompany(), user, taskOld.getId());

        List<TaskFeedback> list = new ArrayList<TaskFeedback>();
        if (searchResult != null) {
            list = searchResult.getList();
            for (TaskFeedback entity : list) {
                entity.setTask(task);
                taskFeedbackService.update(entity);
            }
        }*/

        return ajaxJson(resultService.success("操作成功！"));
    }

    /**
     * 保存相关附件
     */
    @RequestMapping(value = "uploadfile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object saveFiles(@CurrentUser User user, String fileIds, String keyId) {

        Task task = taskService.get(keyId);

        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
            task.setFile(fileManageList);
        }

        return ajaxJson(taskService.saveEntity(task));
    }

    /**
     * 保存关联任务
     */
    @RequestMapping(value = "saverelate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object saveRelate(@CurrentUser User user, String relateTaskIds, String keyId) {

        Task task = taskService.get(keyId);

        if(StringUtils.isNotBlank(relateTaskIds)){
            String[] tasks = StringUtils.split(relateTaskIds,",");
            HashSet<Task> objs = new HashSet<Task>();
            for (String id : tasks) {
                Task relateTask = taskService.get(id);
                if (!relateTask.getId().equals(task.getId())){
                    objs.add(relateTask);
                }
            }
            task.setRelateTasks(objs);
        }

        return ajaxJson(taskService.saveEntity(task));
    }

    /**
     * 状态变更选择框
     */
    @RequestMapping(value = "scdialogs", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String scdialogs(@CurrentUser User user,@RequestParam(required = false) String taskId, Model model) {
        model.addAttribute("taskId",taskId);

        return "/com/task_scdialogs";
    }

    /**
     * 任务日历
     */
    @RequestMapping(value = "calendar", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String calendar(@CurrentUser User user,@RequestParam(required = false) String prjId, Model model) {
        model.addAttribute("prjId",prjId);

        return "/com/task_calendar";
    }

    /**
     * 任务组员选择框
     */
    @RequestMapping(value = "member", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String member(@CurrentUser User user,@RequestParam(required = false) String prjId, Model model) {
        Company company = user.getCompany();

        List<Rule> rules = new ArrayList<Rule>();
        rules.add(RuleHelper.ne("txtStatus", "历史"));
        if (!StringUtils.isEmpty(prjId)) {
            rules.add(RuleHelper.eq("dictItem.id", prjId));   // 所属项目
        }

        SearchResultPaging searchResult = taskService.findPagingBySearch(null, rules, null);

        List<Task> entityList = new ArrayList<Task>();
        if (searchResult != null) {
            entityList = searchResult.getList();
        }

        Set<User> users = new HashSet<User>();
        for (Task entity: entityList) {
            if (entity.getLeaders()!=null) {
                users.addAll(entity.getLeaders());
            }
            if (entity.getMembers()!=null) {
                users.addAll(entity.getMembers());
            }
        }

        model.addAttribute("users",users);
        return "/com/task_member_dialog";
    }

    /**
     * 状态变更
     */
    @RequestMapping(value = "scsave", method = RequestMethod.POST)
    public Object saveDialogReturn(@CurrentUser User user,String taskId,String txtStatus) throws ParseException {
        Task task = taskService.get(taskId);

        if (task==null) {
            return resultService.fail("对应的业务数据已丢失！");
        }

        if (StringUtils.isNotBlank(txtStatus)) {
            task.setTxtStatus(txtStatus);

            if(txtStatus.equals("任务关闭")){
                //发送提醒
                Remind remind = new Remind();
                remind.setUser(task.getCreater());
                remind.setBussinessKey("task");
                remind.setKeyId(task.getId());
                remind.setContent(task.getName()+" 任务已被发起人关闭");
                remindService.save(remind);
            }
        }

        return ajaxJson(taskService.saveEntity(task));
    }

    /**
     * 某一任务的相关任务列表
     */
    @RequestMapping(value = "listR", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> listR(@CurrentUser User user,
                                     @RequestParam() String taskId) {

        Task task = taskService.get(taskId);
        Set<Task> dataList = task.getRelateTasks();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();

        Map<String,Object> rMap;
        for (Task entity : dataList) {
            rMap = new HashMap<String, Object>();
            rMap.put("id",entity.getId());
            rMap.put("dictItemName",entity.getDictItem().getName());
            rMap.put("name",entity.getName());
            String leaders="";
            for(User user1:entity.getLeaders()){
                leaders+=user1.getName()+",";
            }
            rMap.put("leaders",leaders.substring(0, leaders.length() - 1));
            rMap.put("datPlanStart",DataUtil.DateToString(entity.getDatPlanStart()));
            rMap.put("datPlanEnd",DataUtil.DateToString(entity.getDatPlanEnd()));
            switch (entity.getPriority()){
                case 0:rMap.put("priority","一般");break;
                case 1:rMap.put("priority","重要");break;
                case 2:rMap.put("priority","紧急");break;
            }
            rMap.put("txtStatus",entity.getTxtStatus());
            rMap.put("dateApply",DataUtil.DateToString(entity.getCreateTime()));
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", 1);
        data.put("rows", 500);

        if (dataList == null) {
            data.put("records", 0);
            data.put("total", 0);
        } else {
            int c = dataList.size();
            data.put("records", c);
            data.put("total", c);
        }

        return data;
    }

    /**
     * 选择任务(多个)
     */
    @RequestMapping(value = "dialogs", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialogs(@CurrentUser User user,@RequestParam(required = false) String sids, Model model) {
        model.addAttribute("sids", sids);

        if (StringUtils.isNotBlank(sids)) {
            String[] uids = StringUtils.split(sids, ",");
            ArrayList<Task> tasks = new ArrayList<Task>();
            for (String uid : uids) {
                Task u = taskService.get(uid);
                tasks.add(u);
            }
            model.addAttribute("selectedTasks", tasks);
        }

        return "/com/task_dialogs";
    }

    /**
     * 相关附件页面
     */
    @RequestMapping(value = "toFile", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String toFile(@CurrentUser User user, Model model,String parentId) {
        if(StringUtils.isNotEmpty(parentId)) {
            String fileId ="";
            Task task = taskService.get(parentId);
            if(task.getFile() != null && task.getFile().size()>0){
                for(FileManage f:task.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("fileId", fileId);
        }
        return "/com/task_file";
    }

    /**
     * 获取字典
     */
    @RequestMapping(value = "getTaskDict",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
    public Object getTaskDict(@CurrentUser User user){
        ArrayList<DictItem> dictItems = getDictItems(user,"taskPrj");
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("dict",dictItems);
        return ajaxJson(map);
    }


}
